<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

use App\Models\UserScoreLog;
use App\Models\Luo;
use App\Models\LuoUser;
use App\Events\UserScoreUpdateEvent;

class User extends Model {

    use SoftDeletes;

    const USER_ACTIVE = 1;

    protected $fillable = ['name', 'email', 'tel', 'password', 'meta'];
    protected $dates = ['deleted_at'];

    public static function login($data) {
        $u = User::where('name', $data['account'])->orWhere('email', $data['account'])->orWhere('tel', $data['account'])->first();
        if($u && $u->password == md5($data['password'])) return $u;
    }

    public static function check($data) {
        $u = User::where('name', $data['username'])->orWhere('email', $data['email'])->orWhere('tel', $data['tel'])->first();
        if($u && $u->name == $data['username']) return '用户名已存在';
        if($u && $u->email == $data['email']) return '邮箱已存在';
        if($u && $u->tel == $data['tel']) return '电话已存在';
        return false;
    }

    public static function add($data) {
        $meta = [
            'luo_pro'   =>  $data['luo_pro'],
            'luo_city'  =>  $data['luo_city'],
            'job'       =>  $data['job'],
        ];
        $u = User::create([
            'name'  =>  $data['username'],
            'email' =>  $data['email'],
            'tel'   =>  $data['tel'],
            'password'  =>  md5($data['password']),
            'meta'  =>  serialize($meta),
        ]);
        return $u;
    }

    public function is_active() {
        return $this->status == User::USER_ACTIVE;
    }

    public function status() {
        switch($this->status) {
            case 0: return '未审核';
            case 1: return '审核通过';
        }
    }

    public function update_score($event) {
        $step = UserScoreUpdateEvent::get_step($event);
        UserScoreLog::add($this->id, $event, $step);
        $this->score += $step;
        $this->save();
        return $this->score;
    }

    public function luo_relation() {
        return $this->hasOne('App\Models\LuoUser', 'uid', 'id');
    }

    public function get_luo() {
        $this->load('luo_relation');
        return $this->luo_relation? $this->luo_relation->luo: null;
    }

    public function join(Luo $luo) {
        LuoUser::add($this, $luo);
        if($this->status == 0) {
            $this->status = User::USER_ACTIVE;
            $this->save();
            event(new UserScoreUpdateEvent($this, UserScoreUpdateEvent::USER_REVIEWED_EVENT));
        }
    }

    public function posts() {
        return $this->hasMany('App\Models\Post', 'uid', 'id');
    }

    public function get_posts($status=null) {
        $conditions = [];
        if($status) $conditions[] = ['status', '=', $status];
        return $this->posts()->where($conditions)->paginate(20);
    }
}
